package com.tyk.bookstore.front.order.strategy.split;


import com.tyk.bookstore.front.order.strategy.split.model.SplitDto;
import com.tyk.bookstore.front.order.strategy.split.model.SplitStock;
import com.tyk.bookstore.front.storage.model.dto.StockMeetDto;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author tyk
 * @description OrderSplitAction
 */
public interface OrderSplitAction {
    /**
     * 拆单
     *
     * @param cneeAddId      收货地址ID
     * @param splitStockList 拆单参数
     * @return 拆单结果
     */
    List<SplitDto> split(Long cneeAddId, List<SplitStock> splitStockList);


    /**
     * 检查是否所有书籍库存均满足要求
     *
     * @param splitStockList 需要的库存
     * @param stockMeetList  现有的库存
     * @return true if meets else false
     */
    default boolean checkStock(List<SplitStock> splitStockList, List<StockMeetDto> stockMeetList) {
        // bookId=>sum(num) 映射
        Map<Long, Long> bsMap = stockMeetList.stream().collect(Collectors.groupingBy(StockMeetDto::getBookId, Collectors.summingLong(StockMeetDto::getNum)));
        // 所有书籍均需满足库存要求
        return splitStockList.stream().allMatch(
                p -> bsMap.containsKey(p.getBookId()) && bsMap.get(p.getBookId()) >= p.getNum()
        );
    }
}
